package com.iwhalecloud.bss.kite.cucc.web.service.func.card;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneFuncProdInstService;
import com.iwhalecloud.bss.kite.client.api.scene.query.IQuerySceneFuncProdInstService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProdAttrVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProdFuncVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.dto.ContextDTO;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProdAttrCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.ProdAttr;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInstFunc;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProdCardAttrService implements IProdCardAttrService {
    @Autowired
    private IQuerySceneInstService querySceneInstService;
    @Autowired
    private IOperateSceneInstService operateSceneInstService;
    @Autowired
    private IOperateSceneFuncProdInstService operateSceneFuncProdInstService;
    @Autowired
    private IQuerySceneFuncProdInstService querySceneFuncProdInstService;
    @Autowired
    private OperateInstAttrService operateInstAttrService;
    @Override
    public List<InstAttrDTO> getAttrsByfuncProdId(String sceneInstId,String accessProdInstId,String funcProdId,String isEdit) {
        ContextDTO context = KiteWebContext.getContext();
        String custId = context.getCustId();
        String staffId = KiteStringUtils.valueOf(ContextUtil.getUserId());
        String tempInitId = querySceneInstService.getExtParameterValue(sceneInstId,LocalKeyConsts.TEMP_INIT_INST_ID);
        boolean isAdd = KiteStringUtils.isEmpty(tempInitId);
        if(isAdd){
            ProdFuncVO prodFunc = operateSceneFuncProdInstService
                .addFuncProdInst(sceneInstId, accessProdInstId, funcProdId, custId,
                    staffId).getResultObject();
            tempInitId = prodFunc.getProdInstId();
            operateSceneInstService.putExtParameter(sceneInstId, LocalKeyConsts.TEMP_INIT_INST_ID,tempInitId);
        }
        List<InstAttrDTO> dtoList = querySceneFuncProdInstService
            .listProdInstFuncAttrs(sceneInstId,custId, tempInitId, "F").getResultObject();
        if(!isAdd){//不是新打开窗口时调用 清空属性值
            for(InstAttrDTO instAttrDTO : dtoList){
                if(!KiteStringUtils.equalsAny(instAttrDTO.getAttrValueTypeId(),"98R","98A")){
                    instAttrDTO.setValue(null);
                    instAttrDTO.setValueDesc(null);
                    instAttrDTO.setDefaultValue(null);
                }
            }
        }
        return dtoList;
    }

    @Override
    public Map<String, List> getInstTab(String sceneInstId, String funcProdId, String accessProdInstId,String initInstId,String isEdit,String custId) {
        Map<String,List> tabMap = new HashMap<>();
        //获取当前删除标记实例 前端不展示
        String tempDelId = querySceneInstService.getExtParameterValue(sceneInstId,LocalKeyConsts.TEMP_DEL_INST_ID);
        String tempInitId = querySceneInstService.getExtParameterValue(sceneInstId,LocalKeyConsts.TEMP_INIT_INST_ID);
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        if(KiteStringUtils.isEmpty(tempInitId)){
            tempInitId = initInstId;
        }
        KiteProdInst accessProdInst = querySceneInstService.getProdInst(custId, accessProdInstId);
        List<KiteProdInstFunc> prodFuncInstList = querySceneInstService.listProdInstFuncsByProdId(custId, accessProdInstId, funcProdId);
       // List<ProdAttr> prodAttrList = Optional.ofNullable(ProdAttrCache.get(funcProdId)).orElse(Lists.newArrayList());
        //List<ProdAttrVO> titleProdAttr = KiteBeanUtils.copyPropsForList(prodAttrList, ProdAttrVO.class);
        //获取表格id
        List<KiteAttr> commonAttrs = querySceneInstService.listCommonAttrsByObjId(sceneInstId, funcProdId);
        //String[]cardInstAry =   cardInstIds.split(",");
        List<Map<String,String>> tabCols = new ArrayList<>();
        commonAttrs.forEach(commonAttr->{
            Map<String,String> tabcol = new HashMap<>();
            tabcol.put("dataIndex", commonAttr.getFieldName());
            tabcol.put("title", commonAttr.getCname());
            tabCols.add(tabcol);
        });
        if(KiteListUtils.isNotEmpty(prodFuncInstList)){
            List<Map<String,Object>> tabVals  = new ArrayList<>();
            for(KiteProdInstFunc kiteProdInstFunc:prodFuncInstList){
                //保存原值
                List<KiteAttr> kiteAttrList = kiteProdInstFunc.listAttrs();
                this.saveBeforeEditAttr(isEdit, sceneInstId, kiteProdInstFunc.getProdInstId(), kiteAttrList);
                if((KiteStringUtils.isNotEmpty(tempDelId)&&tempDelId.contains(kiteProdInstFunc.getProdInstId()))||KiteStringUtils.equals(tempInitId,kiteProdInstFunc.getProdInstId())){
                    continue;
                }
                //KiteProdInstFunc kiteProdInstFunc = querySceneInstService.getProdInstFunc(custId, cardInstId);
                Map<String,Object> tabVal = new HashMap<>();
                commonAttrs.forEach(commonAttr->{
                    if(!KiteStringUtils.equals(commonAttr.getFieldName(),"actionType")){
                        KiteAttr tempAttr = kiteProdInstFunc.getAttr(commonAttr.getFieldName());
                        if(!KiteStringUtils.equals(commonAttr.getAttrValueTypeId(),tempAttr.getAttrValueTypeId())){
                            tempAttr.setAttrValueTypeId(commonAttr.getAttrValueTypeId());
                        }
                        tabVal.put(commonAttr.getFieldName(),tempAttr);
                    }
                });
                tabVal.put("actionType",getActionTypeName(kiteProdInstFunc.getActionType().name()));
                tabVal.put("prodInstId",kiteProdInstFunc.getProdInstId());
                setTabCtrl(tabVal,isEdit,accessProdInst,kiteProdInstFunc,sceneInst.getServiceOfferId());
                tabVals.add(tabVal);
            }
            tabMap.put("tableValue", tabVals);
            tabMap.put("tableCol", tabCols);
        }
        return tabMap;
    }


    public List<KiteProdInstFunc> saveProdFuncBatch(String sceneInstId,String accessProdInstId,String funcProdId){
        ContextDTO context = KiteWebContext.getContext();
        String custId = context.getCustId();
        String staffId = KiteStringUtils.valueOf(ContextUtil.getUserId());
        String tempInitId = querySceneInstService.getExtParameterValue(sceneInstId,LocalKeyConsts.TEMP_INIT_INST_ID);//初始实例
        //String tempEditId = querySceneInstService.getExtParameterValue(sceneInstId,"TEMP_EDIT_INST_ID");//编辑实例
        KiteProdInstFunc kiteProdInstFunc = querySceneInstService.getProdInstFunc(custId, tempInitId);
        //Map<String, KiteAttr> attrMap = kiteProdInstFunc.getAttrMap();
        //Set<Map.Entry<String, KiteAttr>> attrEn = attrMap.entrySet();
        List<KiteAttr> attrList = kiteProdInstFunc.listAttrs();
        //List<KiteAttr> attrList = querySceneFuncProdInstService.listProdInstFuncKiteAttrs(sceneInstId, custId, tempInitId, "T").getResultObject();
        KiteAttr batchAttr = attrList.stream().filter(attr -> KiteStringUtils.equals(attr.getAttrValueTypeId(), "98K")).findFirst().orElse(null);
        //所有的功能产品实例
        //List<KiteProdInstFunc> prodFuncInstList = querySceneInstService.listProdInstFuncsByProdId(custId, accessProdInstId, funcProdId);
        List<KiteProdInstFunc> prodFuncs = Lists.newArrayList();
        if(Objects.nonNull(batchAttr)){
            String [] batchValues = batchAttr.getValue().split(",");
            String [] batchValueDescs = batchAttr.getValueDesc().split(",");
            for (int i =0;i<batchValues.length;i++){
                //String batchVal = batchValues[i];
                //KiteProdInstFunc prodInstFunc = prodFuncInstList.stream().filter(prodFuncInst -> KiteStringUtils.equals(prodFuncInst.getAttrValue(batchAttr.getFieldName()), batchVal)&&!KiteStringUtils.equals(tempInitId,prodFuncInst.getProdInstId())).findFirst().orElse(null);
                //boolean addFlag = false;//是否是添加
                //if(Objects.isNull(prodInstFunc)&&KiteStringUtils.isEmpty(tempEditId)){
/*                if(Objects.isNull(prodInstFunc)){
                    ProdFuncVO prodFunc = operateSceneFuncProdInstService.addFuncProdInst(sceneInstId, accessProdInstId, funcProdId, KiteWebContext.getContext().getCustId(),
                            staffId).getResultObject();
                    prodInstFunc = querySceneInstService.getProdInstFunc(custId, prodFunc.getProdInstId());
                    addFlag = true;
                }*/
/*                if(KiteStringUtils.isNotEmpty(tempEditId)){
                    prodInstFunc = querySceneInstService.getProdInstFunc(custId, tempEditId);
                }*/
                ProdFuncVO prodFunc = operateSceneFuncProdInstService.addFuncProdInst(sceneInstId, accessProdInstId, funcProdId, KiteWebContext.getContext().getCustId(),
                    staffId).getResultObject();
                KiteProdInstFunc prodInstFunc = querySceneInstService.getProdInstFunc(custId, prodFunc.getProdInstId());
                for( KiteAttr kiteAttr:attrList){
                    if(KiteStringUtils.equalsAny(kiteAttr.getShowType(),"E")){
                        continue;
                    }
                    String attrValue = kiteAttr.getValue();
                    String attrValueDesc = kiteAttr.getValueDesc();
                    if(KiteStringUtils.equals(kiteAttr.getFieldName(),batchAttr.getFieldName())){
                        attrValue = batchValues[i];
                        attrValueDesc = batchValueDescs[i];
                    }
                    //if(!addFlag&&KiteStringUtils.isEmpty(tempEditId)){
/*                    if(!addFlag){
                        if(KiteStringUtils.equals(kiteAttr.getAttrValueTypeId(),"98C")&&KiteStringUtils.isNum(attrValue)){
                            attrValue = addNum(attrValue,prodInstFunc.getAttrValue(kiteAttr.getFieldName()));
                            attrValueDesc = addNum(attrValueDesc,prodInstFunc.getAttrValueDesc(kiteAttr.getFieldName()));
                        }
                    }*/
                    operateSceneFuncProdInstService.updateFuncProdInstAttr(KiteWebContext.getContext().getCurrentSceneInstId(), accessProdInstId, prodInstFunc.getProdInstId(),
                        kiteAttr.getFieldName(), attrValue, attrValueDesc, KiteWebContext.getContext().getCustId(),
                        ContextUtil.getSimpleLoginInfo().getStaffId().toString(), null);
                }
                prodFuncs.add(prodInstFunc);
            }
        }else{
            ProdFuncVO prodFunc = operateSceneFuncProdInstService
                .addFuncProdInst(sceneInstId, accessProdInstId, funcProdId, KiteWebContext.getContext().getCustId(),
                    staffId).getResultObject();
            for(KiteAttr kiteAttr:attrList){
                String attrValue = kiteAttr.getValue();
                String attrValueDesc = kiteAttr.getValueDesc();
                operateSceneFuncProdInstService.updateFuncProdInstAttr(KiteWebContext.getContext().getCurrentSceneInstId(), accessProdInstId, prodFunc.getProdInstId(),
                    kiteAttr.getFieldName(), attrValue, attrValueDesc, KiteWebContext.getContext().getCustId(),
                    ContextUtil.getSimpleLoginInfo().getStaffId().toString(), null);
            }
        }
        return prodFuncs;
    }
    private void filterAttr(List<KiteAttr> attrs){

    }

    private  String getActionTypeName(String actionType) {
        String actionTypeName;
        switch (actionType) {
            case "A":
                actionTypeName = "新增";
                break;
            case "M":
                actionTypeName = "修改";
                break;
            case "D":
                actionTypeName = "删除";
                break;
            case "K":
                actionTypeName = "原有";
                break;
            case "X":
                actionTypeName = "成员退出5G切片";
                break;
            default:
                actionTypeName = "删除(A->D)";
                break;
        }
        return actionTypeName;
    }
    private  String addNum(String oldNum,String addNum){
        int oldNumInt = Integer.parseInt(oldNum);
        int addNumInt = Integer.parseInt(addNum);
        int resNum = oldNumInt+addNumInt;
        return String.valueOf(resNum);
    }
    private void setTabCtrl(Map<String,Object> tabVal,String isEdit,KiteProdInst accessProdInst ,KiteProdInstFunc kiteProdInstFunc,String ServiceOfferId){
        if(KiteStringUtils.equals(isEdit,"T")){
            tabVal.put("isDel", "T");
            tabVal.put("isEdit", "T");
        }else{
            tabVal.put("isDel", "F");
            tabVal.put("isEdit", "F");
        }
        List<DcPublic> dcPublics = DcPublicCache.getByPkey("2021110307", accessProdInst.getProdId());
        if(KiteListUtils.isNotEmpty(dcPublics)&&KiteStringUtils.equals(isEdit,"T")){
            DcPublic dcPublic = dcPublics.stream().filter(dc -> KiteStringUtils.equalsAny(dc.getPcode(),kiteProdInstFunc.getProdId(), SymbolConsts.STAR)&&KiteStringUtils.equals(ServiceOfferId, dc.getCodea())).findFirst().orElse(null);
            if(Objects.nonNull(dcPublic)){
                String codeb = dcPublic.getCodeb();
                if(KiteStringUtils.isNotEmpty(codeb)){
                    JSONObject codebJson = JSONObject.parseObject(codeb);
                    Set<Map.Entry<String, Object>> entries = codebJson.entrySet();
                    entries.forEach(dcFld->{
                        String fldName = dcFld.getKey();
                        String fldVal = (String) dcFld.getValue();
                        String[] fldVals = fldVal.split(",");
                        if(KiteStringUtils.equalsAny(kiteProdInstFunc.getAttrValue(fldName),fldVals)){
                            tabVal.put("isDel", dcPublic.getCodec());
                            tabVal.put("isEdit", dcPublic.getCoded());
                        }
                    });
                }else {
                    tabVal.put("isDel", "F");
                    tabVal.put("isEdit", "T");
                }
            }
        }
    }
    private void saveBeforeEditAttr(String isEdit, String sceneInstId, String prodInstId, List<KiteAttr> kiteAttrList) {
        if (!KiteStringUtils.equals(isEdit, KeyConsts.IFTRUE_T)) {
            return;
        }
        IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);
        operateSceneInstService.putExtParameter(sceneInstId, prodInstId, kiteAttrList);
    }
}
